# utils/exporter.py
import csv


def export_to_csv(items: list, filename: str, columns: list):
    if not items:
        return False
    try:
        with open(filename, "w", encoding="utf-8-sig", newline="") as f:
            writer = csv.DictWriter(f, fieldnames=columns, quoting=csv.QUOTE_ALL)
            writer.writeheader()
            for item in items:
                # Ensure all keys are present
                row = {col: str(item.get(col.lower(), "")).replace("\n", " ").replace("\r", " ") for col in columns}
                writer.writerow(row)
        return True
    except Exception as e:
        print(f"[导出错误] {e}")
        return False